package com.ws.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.common.ResultUtils;
import com.domain.dto.UserShowInfo;
import com.domain.entity.ApplyFriend;
import com.service.TeamService;
import com.ws.SessionManager;
import com.ws.event.FriendEvent;
import com.ws.event.TeamEvent;
import com.ws.message.ChatMessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class SystemAdvice {
    @Autowired
    TeamService teamService;
    @Autowired
    SessionManager sessionManager;

    /**
     * 监听队伍通知事件，用于发布队伍通知消息
     *
     * @param event
     */
    @EventListener
    public void teamEvent(TeamEvent event) {
        ChatMessageVo chatMessageVo = BeanUtil.copyProperties(event, ChatMessageVo.class);
        chatMessageVo.setText(event.getSender().getUsername() + event.getStatus());
        List<UserShowInfo> teamMember = teamService.getTeamMember(event.getReceiverId());
        List<Long> memeberIds = teamMember.stream().map(UserShowInfo::getId).collect(Collectors.toList());
        sessionManager.sendBatchMessage(JSONUtil.toJsonStr(ResultUtils.success(chatMessageVo)),
                (ArrayList<Long>) memeberIds,
                event.getReceiverId());
    }

    @EventListener
    public void friendEvent(FriendEvent event) {
        ChatMessageVo chatMessageVo = BeanUtil.copyProperties(event, ChatMessageVo.class);
        ApplyFriend applyFriend = event.getApplyFriend();
        chatMessageVo.setText(applyFriend.getText());
        sessionManager.sendMessage(JSONUtil.toJsonStr(ResultUtils.success(chatMessageVo)),event.getReceiverId());

    }

}
